package com.android.questions.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import com.android.base.util.ActivityClickUtil;
import com.android.base.util.DQLog;
import com.android.base.util.DisplayUtil;
import com.android.base.util.SystemUtil;
import com.android.base.util.ToastUtil;
import com.android.questions.R;
import com.android.questions.config.AppConfig;
import com.android.questions.config.LoginConfig;
import com.android.questions.databinding.DialogInviteBinding;
import com.android.questions.ui.activity.InviteRecordActivity;
import com.android.questions.ui.adapter.InviteAdapter;
import com.android.questions.util.sound.MediaBackManager;
import com.bumptech.glide.Glide;
import com.dq.ad.AdManager;
import com.dq.ad.UMManager;
import com.hx.currency.HXCurrencySDK;
import com.hx.currency.data.api.BaseResp;
import com.hx.currency.data.qa.api.QAInviteConfigResp;
import com.hx.currency.data.qa.model.QAInvite;
import com.qq.e.o.ads.v2.error.AdError;
import com.qq.e.o.data.HttpUtil;
import com.qq.e.o.utils.JsonUtil;

import java.util.List;

/**
 * FileName: DialogInvite
 * Author: admin
 * Date: 2022/1/23 14:33
 * Description:
 */
public class DialogInvite extends Dialog implements View.OnClickListener {

    private DialogInviteBinding inviteBinding;
    private OnClickLister clickLister;
    private final Activity activity;
    private InviteAdapter inviteAdapter;
    private String inviteCode;
    private boolean isReward;

    public DialogInvite(Activity act) {
        super(act, R.style.dialog_loading);
        this.activity = act;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inviteBinding = DialogInviteBinding.inflate(activity.getLayoutInflater());
        setContentView(inviteBinding.getRoot());

        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = DisplayUtil.getScreenWidth(activity);
        lp.height = DisplayUtil.getScreenHeight(activity);
        getWindow().setAttributes(lp);

        getWindow().setWindowAnimations(R.style.dialog_answer_correct);

        setCancelable(false);
        setCanceledOnTouchOutside(false);

        initView();
        initListener();
    }

    private void initView() {
        inviteAdapter = new InviteAdapter();
        inviteBinding.rvInvite.setAdapter(inviteAdapter);
        inviteAdapter.setClickLister(new InviteAdapter.OnItemChildClickLister() {
            @Override
            public void onWithdrawal(QAInvite item, int pos) {
                watchVideoAd(item, pos);
            }

            @Override
            public void onInvite() {
                dismiss();
                if (clickLister != null) {
                    clickLister.onInvite(inviteCode);
                }
            }
        });

        Glide.with(activity)
                .load(LoginConfig.getUserHeadUrl())
                .error(R.drawable.icon_user_default_header)
                .placeholder(R.drawable.icon_user_default_header)
                .into(inviteBinding.ivAvatar);
    }

    private void initListener() {
        inviteBinding.ivClose.setOnClickListener(this);
        inviteBinding.tvInviteRecord.setOnClickListener(this);
        inviteBinding.ivJoinQqGroup.setOnClickListener(this);
        inviteBinding.ivInviteNow.setOnClickListener(this);
    }

    private void watchVideoAd(QAInvite item, int pos) {
        isReward = false;
        if (AppConfig.hasNoAd()) {
            withdrawal(item.getIid(), item.getWa(), pos);
        } else {
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    if (isReward) {
                        withdrawal(item.getIid(), item.getWa(), pos);
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，提现失败");
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    withdrawal(item.getIid(), item.getWa(), pos);
                }

                @Override
                public void onTimeout() {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    withdrawal(item.getIid(), item.getWa(), pos);
                }
            });
        }
    }

    /**
     * 提现
     *
     * @param taskId       对应任务id
     * @param rewardAmount 任务奖励金额
     */
    private void withdrawal(int taskId, double rewardAmount, int pos) {
        HXCurrencySDK.getInstance().qaInviteReceive(taskId, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("邀请提现结果：" + response);
                BaseResp baseResp = JsonUtil.parseObject(response, BaseResp.class);
                if (baseResp != null) {
                    int errorCode = baseResp.getErrorCode();
                    if (errorCode == 0) {
                        withdrawalSuccess(false, rewardAmount, pos);
                    } else if (errorCode == 10025) {
                        new DialogWithError(activity).setType(DialogWithError.TYPE_QUEUE).show();
                    } else if (errorCode == 10026) {
                        withdrawalSuccess(true, rewardAmount, pos);
                    } else if (errorCode == 10028) {
                        new DialogWithError(activity).show();
                    } else {
                        ToastUtil.showShortToastCenter(activity, baseResp.getErrorMessage());
                    }
                } else {
                    ToastUtil.showShortToastCenter(activity, "提现失败");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("邀请提现失败：" + throwable.toString());
                ToastUtil.showShortToastCenter(activity, "网络异常，提现失败");
            }
        });
    }

    private void withdrawalSuccess(boolean isQueue, double rat, int pos) {
        getInvitedData();
        int remainWithdrawalTimes = AppConfig.getRemainWithdrawalTimes();
        if (remainWithdrawalTimes >= 1) {
            AppConfig.setRemainWithdrawalTimes(remainWithdrawalTimes - 1);
        }
        switch (pos) {
            case 0:
                UMManager.onEvent(UMManager.Event.InvitationRewards_success_1);
                break;
            case 1:
                UMManager.onEvent(UMManager.Event.InvitationRewards_success_2);
                break;
            case 2:
                UMManager.onEvent(UMManager.Event.InvitationRewards_success_3);
                break;
            case 3:
                UMManager.onEvent(UMManager.Event.InvitationRewards_success_4);
                break;
            case 4:
                UMManager.onEvent(UMManager.Event.InvitationRewards_success_5);
                break;
            case 5:
                UMManager.onEvent(UMManager.Event.InvitationRewards_success_6);
                break;
        }
        new DialogWithdrawalSuccess(activity).setCash(rat).setQueue(isQueue).setClickLister(new DialogWithdrawalSuccess.OnClickLister() {
            @Override
            public void onWithdrawal() {
                // 继续赚钱
            }
        }).show();
    }

    private void getInvitedData() {
        HXCurrencySDK.getInstance().getQaInviteConfig(new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String s) {
                DQLog.e("邀请配置获取成功：" + s);
                QAInviteConfigResp qaInviteConfigResp = JsonUtil.parseObject(s, QAInviteConfigResp.class);
                if (qaInviteConfigResp != null && qaInviteConfigResp.getErrorCode() == 0) {
                    inviteCode = qaInviteConfigResp.getIc();
                    inviteBinding.labelRule11.setText(qaInviteConfigResp.getIvc() + "");
                    updateUI(qaInviteConfigResp.getIn(), qaInviteConfigResp.getIl());
                } else {
                    updateUI(0, null);
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("邀请配置获取失败：" + throwable.getMessage());
                updateUI(0, null);
            }
        });
    }

    private void updateUI(int inviteCount, List<QAInvite> list) {
        if (list != null && list.size() > 0) {
            inviteAdapter.setInviteCount(inviteCount);
            inviteAdapter.setList(list);
            inviteAdapter.notifyDataSetChanged();
            inviteBinding.tvInviteCount.setText(inviteCount + "");
            inviteBinding.rvInvite.setVisibility(View.VISIBLE);
        } else {
            inviteBinding.rvInvite.setVisibility(View.GONE);
        }
    }

    public DialogInvite setClickLister(OnClickLister lister) {
        this.clickLister = lister;
        return this;
    }

    @Override
    public void onClick(View v) {
        if (ActivityClickUtil.getInstance().isFastClick()) {
            //防止用户快速点击
            return;
        }
        if (v.getId() == R.id.tv_invite_record) {
            InviteRecordActivity.startActivity(activity);
        } else if (v.getId() == R.id.iv_join_qq_group) {
            SystemUtil.joinQQGroup(activity, AppConfig.QQ_GROUP_KEY);
        } else if (v.getId() == R.id.iv_invite_now) {
            dismiss();
            if (clickLister != null) {
                clickLister.onInvite(inviteCode);
            }
        } else if (v.getId() == R.id.iv_close) {
            dismiss();
        }
    }

    public interface OnClickLister {
        void onInvite(String inviteCode);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        // hasFocus 是否回到当前对话框界面
        if (hasFocus) {
            getInvitedData();
        }
    }
}